package top.laoshuzi.server.camera.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class SimpleMqttClientImpl implements SimpleMqttClient {

    private MqttClient mqttClient = null;

    private String clientId;
    private MqttConnectOptions connectOptions;


    private String host;
    private int port;

    public SimpleMqttClientImpl(String username, String password, int keepAliveInterval, int connectionTimeout) {
        MqttConnectOptions option = new MqttConnectOptions();
        option.setUserName(username);
        option.setPassword(password.toCharArray());
        option.setConnectionTimeout(connectionTimeout);
        option.setKeepAliveInterval(keepAliveInterval);
        option.setAutomaticReconnect(true);
        option.setCleanSession(true);
    }

    @Override
    public void connect(String serverURI, String clientId, MqttCallback mqttCallback) {

        try {
            mqttClient = new MqttClient(serverURI, clientId, new MemoryPersistence());
            mqttClient.setCallback(mqttCallback);
            mqttClient.connect(connectOptions);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void disconnect() {
        try {
            mqttClient.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void subscribe(String topic, int qos) {
    }

    @Override
    public void publish(String topic, byte[] payload) {

    }

    @Override
    public void publish(String topic, byte[] payload, int qos, boolean retained) {
        MqttMessage message = new MqttMessage();
        message.setPayload(payload);
        message.setQos(qos);
        message.setRetained(retained);
    }
}
